<template>
  <div class="project_page">
    <div class="self-buying">
      <h2>
        自购分佣
        <span>（开启后分销员会同自己绑定关系，自购会给自己返佣，上级也会获得间接分佣）</span>
      </h2>
      <span class="switch">自购分佣</span>
      <el-radio-group v-model="form.ifSelf" @change="ruty">
        <el-radio :label="1">开启</el-radio>
        <el-radio :label="0">关闭</el-radio>
      </el-radio-group>
    </div>
    <div class="level_content">
      <h2>
        分销员等级
        <span>（满足规则后分销员自动升级、等级编号越大，级别越高）</span>
      </h2>
      <el-table v-loading="tableLoading" :data="tableData" border style="width: 100%">
        <el-table-column prop="levelNum" label="等级编号" width="150" />
        <el-table-column prop="levelName" label="等级名称" />
        <el-table-column prop="levelLogo" label="等级图标">
          <template #default="scope">
            <img :src="scope.row.levelLogo" class="avatar" />
          </template>
        </el-table-column>
        <el-table-column label="升级规则" width="380">
          <template #default="scope">
            <div>
              <div v-if="scope.row.conditionMoney != null">
                累计直接分销金额满{{ scope.row.conditionMoney }}元
              </div>
              <div v-if="scope.row.conditionInvitation != null">
                邀请下级满{{ scope.row.conditionInvitation }}人
              </div>
              <div v-if="scope.row.conditionCustomer != null">
                客户满{{ scope.row.conditionCustomer }}人
              </div>
              <!-- <div>{{scope.row.rule}}</div> -->
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="directProportion" label="直接分佣比例">
          <template #default="scope">
            <span>{{ scope.row.directProportion + '%' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="indirectProportion" label="间接分佣比例">
          <template #default="scope">
            <span>{{ scope.row.indirectProportion + '%' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button link type="primary" @click.native.prevent="edit(scope.row.distributorLevelId)">编辑</el-button>
            <el-button link type="primary" @click.native.prevent="deletes(scope.row.distributorLevelId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" class="subm" @click="add">添加等级</el-button>
    </div>
    <el-dialog
      v-model="visible"
      :title="form.distributorLevelId?'编辑等级':'添加等级'"
      width="30%"
      center
      :close-on-click-modal="false"
      @closed="closed(formRef)"
    >
      <div>
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
        >
          <el-form-item label="等级编号" prop="levelNum">
            <el-input v-model="form.levelNum" placeholder="请输入等级编号" maxlength="7" oninput="value=value.replace(/[^\d]/g,'')" />
          </el-form-item>
          <el-form-item label="等级名称" prop="levelName">
            <el-input v-model="form.levelName" placeholder="请输入等级名称" />
          </el-form-item>
          <el-form-item label="等级图标" prop="levelLogo">
            <el-upload
              class="avatar-uploader"
              list-type="picture-card"
              :headers="headers"
              :action="action"
              :show-file-list="false"
              :on-success="handleLevelPreview"
            >
              <img v-if="form.levelLogo" :src="form.levelLogo" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><el-icon-plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="升级规则" prop="conditions" class="escalationRule">
            <el-checkbox-group v-model="form.conditions" @change="checkboxChange">
              <el-checkbox :label="1" border>
                <el-form-item label="" prop="conditionMoney">
                  累计直接分销金额满
                  <el-input-number v-model="form.conditionMoney" :disabled="!form.ifMoney" :precision="2" :controls="false" :max="999999" :min="0" />
                  元
                </el-form-item>
              </el-checkbox>
              <el-checkbox :label="2" border>
                <el-form-item label="" prop="conditionInvitation">
                  邀请下级满
                  <el-input-number v-model="form.conditionInvitation" :disabled="!form.ifInvitation" :precision="0" :controls="false" :max="999999" :min="0" />
                  人
                </el-form-item>
              </el-checkbox>
              <el-checkbox :label="3" border>
                <el-form-item label="" prop="conditionCustomer">
                  客户满
                  <el-input-number v-model="form.conditionCustomer" :disabled="!form.ifCustomer" :precision="0" :controls="false" :max="999999" :min="0" />
                  人
                </el-form-item>
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="直接分佣比例" prop="directProportion">
            <el-input v-model="form.directProportion" placeholder="请输入直接分佣比例"><template #append>%</template></el-input>
          </el-form-item>
          <el-form-item label="间接分佣比例" prop="indirectProportion">
            <el-input v-model="form.indirectProportion" placeholder="请输入间接分佣比例"><template #append>%</template></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" :loading="btnLoading" @click="confirm(formRef)">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onBeforeMount } from 'vue'
import {
  levelGetAll,
  levelAdd,
  levelGetById,
  levelUpdate,
  levelDelete,
  levelUpdateSelf,
} from '@/api/distributor'
import { uploadUrl } from '@/utils/request'
import { getToken } from '@/utils/auth'

const tableData = ref([])
const action = uploadUrl
const headers = {
  'Authorization-business': getToken()
}
const tableLoading = ref(false)
const visible = ref(false)
const btnLoading = ref(false)
const formRef = ref(null)
const form = ref({
  distributorLevelId: null,
  shopId: null,
  ifSelf: 0,
  levelName: '',
  levelNum: '',
  conditions: [],
  ifMoney: 0,
  ifInvitation: 0,
  ifCustomer: 0,
  conditionMoney: null,
  conditionInvitation: null,
  conditionCustomer: null,
  directProportion: '',
  indirectProportion: '',
  levelLogo: ''
})
const checkMoney = (rule, value, callback) => {
  if (form.value.conditions.includes(1) && !value) {
    return callback(new Error('请输入分销金额'))
  } else {
    callback()
  }
}
const checkInvitation = (rule, value, callback) => {
  if (form.value.conditions.includes(2) && !value) {
    return callback(new Error('请输入邀请下级人数'))
  } else {
    callback()
  }
}
const checkCustomer = (rule, value, callback) => {
  if (form.value.conditions.includes(3) && !value) {
    return callback(new Error('请输入客户人数'))
  } else {
    callback()
  }
}
const rules = {
  levelNum: [{ required: true, message: '请输入等级编号', trigger: 'blur' }],
  levelName: [{ required: true, message: '请输入等级名称', trigger: 'blur' }],
  levelLogo: [{ required: true, message: '请上传等级图标', trigger: 'change' }],
  conditionMoney: [{ required: true, validator: checkMoney, trigger: 'blur' }],
  conditionInvitation: [{ required: true, validator: checkInvitation, trigger: 'blur' }],
  conditionCustomer: [{ required: true, validator: checkCustomer, trigger: 'blur' }],
  directProportion: [{ required: true, message: '请输入直接分佣比例', trigger: 'blur' }],
  indirectProportion: [{ required: true, message: '请输入间接分佣比例', trigger: 'blur' }]
}

onBeforeMount(() => {
  getSalesLevel()
})
const handleLevelPreview = (res) => {
  if (res.code === '') {
    form.value.levelLogo = res.data.url
    formRef.value.validateField('levelLogo')
  }
}
const getSalesLevel = () => {
  tableLoading.value = true
  levelGetAll({}).then(res => {
    if (res.code === '') {
      tableData.value = res.data
      form.value.ifSelf = res.data && res.data.length > 0 ? res.data[0].ifSelf : 0
    }
  }).finally(() => {
    tableLoading.value = false
  })
}
const ruty = (index) => {
  levelUpdateSelf({
    ifSelf: index,
  }).then(res => {
    if (res.code === '') {
      ElMessage.success('成功')
    }
  })
}
const add = () => {
  visible.value = true
}
const edit = (id) => {
  levelGetById({ distributorLevelId: id }).then(res => {
    if (res.code === '') {
      form.value = JSON.parse(JSON.stringify(res.data))
      visible.value = true
    }
  })
}
const checkboxChange = (val) => {
  form.value.ifMoney = val.includes(1) ? 1 : 0
  if (!form.value.ifMoney) {
    form.value.conditionMoney = null
  }
  form.value.ifInvitation = val.includes(2) ? 1 : 0
  if (!form.value.ifInvitation) {
    form.value.conditionInvitation = null
  }
  form.value.ifCustomer = val.includes(3) ? 1 : 0
  if (!form.value.ifCustomer) {
    form.value.conditionCustomer = null
  }
}
const confirm = (formEl) => {
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      btnLoading.value = true
      if (form.value.distributorLevelId) {
        levelUpdate(form.value).then((res) => {
          if (res.code === '') {
            ElMessage.success('修改成功')
            getSalesLevel()
            visible.value = false
          }
        }).finally(() => {
          btnLoading.value = false
        })
      } else {
        levelAdd(form.value).then((res) => {
          if (res.code === '') {
            ElMessage.success('新增成功')
            getSalesLevel()
            visible.value = false
          }
        }).finally(() => {
          btnLoading.value = false
        })
      }
    } else {
      return false
    }
  })
}
const reset = () => {
  form.value = {
    distributorLevelId: null,
    shopId: null,
    ifSelf: 0,
    levelName: '',
    levelNum: '',
    conditions: [],
    ifMoney: 0,
    ifInvitation: 0,
    ifCustomer: 0,
    conditionMoney: null,
    conditionInvitation: null,
    conditionCustomer: null,
    directProportion: '',
    indirectProportion: '',
    levelLogo: ''
  }
  form.value.ifSelf = tableData.value.length ? tableData.value[0].ifSelf : 0
}
const closed = (formEl) => {
  formEl.resetFields()
  reset()
}
const deletes = (distributorLevelId) => {
  ElMessageBox.confirm('此操作将永久删除该数据, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      levelDelete({ distributorLevelId }).then((res) => {
        getSalesLevel()
        ElMessage({
          type: 'success',
          message: '删除成功!',
        })
      })
    })
    .catch(() => {})
}
</script>

<style lang="scss" scoped>
.checkList {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px;
  box-sizing: content-box;
  :deep(.el-checkbox__label) {
    flex: 1;
  }
}
h2 {
  font-size: 24px;
  font-weight: 500;
  position: relative;
  padding-left: 40px;
  margin: 20px 0;
  &::before {
    content: '';
    height: 24px;
    width: 4px;
    background-color: #3a68f2;
    position: absolute;
    left: 30px;
    top: 2px;
    display: block;
  }
  span {
    font-size: 14px;
    color: #9a9a9a;
  }
}
.self-buying {
  margin-bottom: 40px;
  .switch {
    margin: 0 20px 0 40px;
  }
}

.level_content {
  .subm {
    width: 100px;
    height: 38px;
    margin-top: 15px;
    border-radius: 4px;
  }

  .level-up-rule {
    width: 340px;
    // overflow-x: scroll;
  }
}
.avatar {
  width: 148px;
  height: 148px;
}
:deep(.el-table) {
  th {
    background: #eef3ff;
    color: #333333;
    font-size: 16px;
    font-weight: 400;
    border-color: #e0e5eb;
    // text-align: center;
  }
  td {
    font-size: 14px;
    // text-align: center;
    color: #666666;
  }
}

:deep(.el-dialog__wrapper) {
  .el-dialog__header {
    height: 70px;
    background-color: #3a68f2;
    .el-dialog__title {
      font-size: 24px;
      color: #fff;
    }
  }
}

:deep(.el-input__inner) {
  height: 30px;
  line-height: 30px;
}
.el-col-8,
.el-row {
  display: flex;
  align-items: center;
  text-align: left;
}
.el-col-4 {
  padding-left: 10px;
}
:deep(.el-form-item__label) {
  font-weight: bold;
}
:deep(.el-checkbox) {
  height: 40px;
  padding: 5px 10px;
  margin-bottom: 15px;
}
:deep(.el-checkbox .el-form-item__error) {
  padding-top: 5px;
}
:deep(.el-checkbox .el-input-number) {
  margin: 0 5px;
  width: 100px;
}
:deep(.el-checkbox:last-of-type) {
  margin-bottom: 0;
}
:deep(.el-checkbox__input.is-checked .el-checkbox__inner,
.el-checkbox__input.is-indeterminate .el-checkbox__inner) {
  background-color: #3a68f2;
  border-color: #3a68f2;
}
:deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
  color: #3a68f2;
}
:deep(.escalationRule .el-form-item) {
  margin-bottom: 0 !important;
}
</style>
